<template>
    <div class="mail-write-fa">
        <div class="mail-write">
            <el-form :model="mailForm" :rules="rules" ref="mailForm">
                <el-form-item label="收件人" prop="toEmail">
<!--                    <el-input v-model="mailForm.toInput" placeholder="请输入收件人（多个邮箱用分号分隔）"-->
                    <el-input v-model="mailForm.toEmail" placeholder="请输入收件人"
                              @focus="show = 'to'"></el-input>
                </el-form-item>
                <!--
                        <el-button @click="showCcBox ?  removeCc():showCc()">
                          {{ showCcBox ? '删除抄送' : '添加抄送' }}
                        </el-button>
                        <el-button @click="showBccBox ?  removeBcc():showBcc()">
                          {{ showBccBox ? '删除密送' : '添加密送' }}
                        </el-button>
                -->
                <div v-show="showCcBox">
                    <el-form-item label="抄送" prop="ccInput">
                        <el-input v-model="mailForm.ccInput" placeholder="请输入抄送人" @focus="show = 'cc'"></el-input>
                    </el-form-item>
                </div>
                <div v-show="showBccBox">
                    <el-form-item label="密送" prop="bccInput">
                        <el-input v-model="mailForm.bccInput" placeholder="请输入密送人" @focus="show = 'bcc'"></el-input>
                    </el-form-item>
                </div>
                <el-form-item label="主题" prop="subject">
                    <el-input v-model="mailForm.subject" placeholder="请输入主题"></el-input>
                </el-form-item>
                <el-upload
                    class="upload-file"
                    action="http://localhost:8989/attachment/upload"
                    :on-change="handleFileChange"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :file-list="fileList"
                    multiple
                    :limit="3"
                    :auto-upload="false"
                    :show-file-list="true"
                    drag
                >
                    <i class="el-icon-link"></i>
                    <div slot="tip" class="el-upload__tip">附件上传</div>
                </el-upload>
                <quill-editor
                    ref="QuillEditor"
                    :options="editorOption"
                    v-model="mailForm.content">
                </quill-editor>
                <div class="mail-footer">
<!--                    <el-button type="warning" @click="submitDraftForm()">保存草稿</el-button>-->
                    <el-button type="primary" @click="submitForm()" style="margin-left: 15vw">发送</el-button>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import {quillEditor} from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import validator from 'validator';
import {mapState} from "vuex";

export default {
    name: 'MailWrite',
    components: {
        quillEditor,
    },
    data() {
        const validateEmail = (rule, value, callback) => {
            const emails = value.split(';');
            const trimmedEmails = emails.map(email => email.trim());
            const uniqueEmails = [...new Set(trimmedEmails)]; // 去除重复项
            // 检查是否有重复的邮箱地址
            if (trimmedEmails.length !== uniqueEmails.length) {
                callback(new Error('邮箱地址中存在重复'));
                return;
            }
            for (const email of emails) {
                if (email.trim() === '') {
                    callback();
                    return;
                }
                if (!validator.isEmail(email.trim())) {
                    callback(new Error('邮箱地址格式不正确'));
                }
            }
            callback();
        };
        return {
            mailForm: {
                toEmail: '',
                ccInput: '',
                bccInput: '',
                subject: '',
                content: '',
            },
            groups: [], // 存储分组信息的数组
            activeNames: [],
            searchQuery: '',
            showCcBox: false,
            showBccBox: false,
            show: '',
            editorOption: {
                placeholder: '请在这里输入',
                theme: 'snow',
            },

            emailId: null,
            fileList: [],
            rules: {
                toInput: [
                    {required: true, message: '请输入收件人', trigger: 'blur'},
                    {validator: validateEmail, trigger: ['blur', 'change']},
                    // 可以添加其他规则，例如非空验证等

                ],
                ccInput: [
                    {required: false, message: '请输入抄送', trigger: 'blur'},
                    {validator: validateEmail, trigger: ['blur']},
                    // 可以添加其他规则，例如非空验证等

                ],
                bccInput: [
                    {required: false, message: '请输入抄送', trigger: 'blur'},
                    {validator: validateEmail, trigger: ['blur']},
                    // 可以添加其他规则，例如非空验证等
                ],
                subject: [
                    {required: false, message: '请输入主题', trigger: 'blur'},
                ],
            }

            // selectedContacts: [], // 存储当前选中的分组下的联系人列表
            // groupId:1,
            // contacts:[],

        };
    },
    created() {
        // this.fetchData();
    },
    watch: {
        // 监听 searchQuery 的变化，当变化时更新 filteredGroups
        searchQuery(newQuery) {
            this.updateFilteredContacts();
        },
    },
    computed: {
        ...mapState(['user']),
        filteredGroups() {
            return this.groups.map(group => ({
                ...group,
                // 过滤每个组的联系人
                filteredContacts: this.filterContactsByQuery(group.contacts)
            }));

        },
    },
    methods: {
        // 点击了 发送邮箱 按钮。
        submitForm() {
            this.$refs.mailForm.validate((valid) => {
                if (valid) {
                    // 表单验证通过，执行发送邮件的逻辑
                    this.sendEmail();

                } else {
                    console.log('表单验证失败');
                    return false;
                }
            });
        },
        // 发送邮箱。
        async sendEmail() {
            // 存草稿
            // await this.saveDraft();
            console.log("emailId，Email: ", this.emailId);
            console.log("emailId，Email: ", this.mailForm);

            this.$store.dispatch('sendEmail', this.mailForm).then(res => {
                // console.log("getContactPage =======> res.data =====>", res);
                if (res !== undefined && res.resultStatus === true) {
                    // console.log("res.resultData", res.resultData);
                    // console.log("res.resultData", res.resultData.records);
                    this.$message.success(res.resultData);
                } else if (res !== undefined && res.resultStatus === false) {
                    // console.log("res.resultData", res.resultData);
                    this.$message.error(res.errorMessage);
                }
            }).catch(res => {
                this.$message.error("后台出问题啦！程序猿小哥正在紧急修复中！！！");
            });


            // await axios.post('http://localhost:8989/email/send?emailId=' + this.emailId).then(response => {
            //     // 假设后端返回的是包含emailId的对象
            //     if (this.$route.name !== 'MailboxList' && this.$route.params.folderId !== 3) {
            //         this.$router.push({path: '/home/mailboxList/3'});
            //         this.$router.go(0);
            //     }
            //
            //     // 跳转路由。
            //     this.emailId = null;
            //     if (this.$route.name !== 'MailboxList' || this.$route.params.folderId !== 3) {
            //         this.$router.push({path: '/mailboxList/3'});
            //     }
            //     console.log("发送成功" + response.data);
            // }).catch(error => {
            //     console.error('发送失败', error);
            //     this.$message.error('发送失败！');
            // });
        },
        // 上传附件。
        async uploadAttachments() {
            if (this.emailId === null) {
                this.$message.error('请先保存草稿！');
                throw new Error('请先保存草稿！');
            }
            const uploadPromises = this.fileList.map(file => {
                // 为每个文件创建一个上传的 Promise
                return new Promise((resolve, reject) => {
                    const formData = new FormData();
                    formData.append('emailId', this.emailId);
                    formData.append('file', file.raw);
                    axios.post('http://localhost:8989/attachment/upload', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(response => {
                        // 处理附件上传成功后的逻辑
                        console.log('附件上传成功');
                        resolve(); // 上传成功，解决 Promise
                    }).catch(error => {
                        // 处理附件上传失败后的逻辑
                        console.error('附件上传失败', error);
                        reject(error); // 上传失败，拒绝 Promise
                    });
                });
            });
            // 使用 Promise.all 等待所有上传完成
            try {
                await Promise.all(uploadPromises);
                console.log('所有附件上传完成');
            } catch (error) {
                console.error('附件上传过程中发生错误', error);
                // 在这里可以处理上传失败的情况，比如通知用户或重试上传
                throw error; // 重新抛出错误，以便在调用 uploadAttachments 的地方能够捕获到
            }
        },




        submitDraftForm() {
            this.$refs.mailForm.validate((valid) => {
                if (valid) {
                    // 表单验证通过，执行发送邮件的逻辑
                    this.saveDraft();
                    if (this.$route.name !== 'MailboxList' || this.$route.params.folderId !== 1) {
                        this.$router.push({path: '/mailboxList/1'});
                    }
                } else {
                    console.log('表单验证失败');
                    return false;
                }
            });
        },
        async fetchData() {
            try {
                // 获取分组列表
                const groupResponse = await axios.get('http://localhost:8989/contact/group?userId=' + this.user.userId);
                console.log(groupResponse.data);
                this.groups = groupResponse.data.map(group => ({
                    ...group,
                    contacts: [], // 初始化每个分组的联系人列表
                }));
                // 遍历分组列表，获取每个分组的联系人

                for (const group of this.groups) {
                    if (group.groupId === 0) {
                        const contactResponse = await axios.get('http://localhost:8989/contact/all_list?userId=' + this.user.userId);
                        group.contacts = contactResponse.data;
                    } else {
                        const contactResponse = await axios.get('http://localhost:8989/contact/group_list?groupId=' + group.groupId);
                        group.contacts = contactResponse.data;
                        console.log("分组内容" + group.contacts);
                        console.log(this.groups);
                    }


                }

            } catch (error) {
                console.error('Error fetching data:', error);
            }
        },
        // 保存草稿
        async saveDraft() {
            console.log("user" + this.user.userId);
            await axios.post('http://localhost:8989/email/draft', {
                fromMail: this.user.userMail,
                toMail: this.mailForm.toInput,
                cc: this.mailForm.ccInput,
                bcc: this.mailForm.bccInput,
                subject: this.mailForm.subject,
                content: this.mailForm.content,
                userId: this.user.userId

            }).then(response => {
                // 假设后端返回的是包含emailId的对象
                this.emailId = response.data;
                if (this.$route.name !== 'MailboxList' && this.$route.params.folderId !== 1) {
                    this.$router.push({path: '/home/mailboxList/1'});
                }
                console.log("草稿emailId" + response.data);
            })
                .catch(error => {
                    console.error('草稿保存失败', error);
                });
            await this.uploadAttachments();
        },

        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);

        },
        handleRemove(file, fileList) {
            const index = this.fileList.indexOf(file);
            if (index !== -1) {
                this.fileList.splice(index, 1);
            }
        },
        handleHeaderClick(groupId) {
            const index = this.activeNames.indexOf(groupId);
            if (index === -1) {
                this.activeNames.push(groupId);
            } else {
                this.activeNames.splice(index, 1);
            }
        },
        showCc() {
            // 添加抄送地址到草稿中的逻辑
            console.log("添加抄送")
            this.showCcBox = true;
            // 隐藏抄送框
        },
        removeCc() {
            // 隐藏抄送框并重置输入框
            this.showCcBox = false;
            this.mailForm.ccInput = '';
        },
        showBcc() {
            // 添加抄送地址到草稿中的逻辑
            console.log("添加密送")
            this.showBccBox = true;
            // 隐藏抄送框
        },
        removeBcc() {
            // 隐藏抄送框并重置输入框
            this.showBccBox = false;
            this.mailForm.bccInput = '';

        },
        handleFileChange(file, fileList) {
            // 更新fileList
            this.fileList = fileList;
        },
        handleUploadSuccess(response, file, fileList) {
            // 处理上传成功后的逻辑（如果需要）
            console.log("上传成功");
        },
        handleUploadError(error, file, fileList) {
            // 处理上传失败后的逻辑
            this.$message.error('上传失败');
        },
        validateField(fieldName) {
            this.$refs.mailForm.validateField(fieldName);
        },
        filterContactsByQuery(contacts) {
            // 根据搜索查询过滤联系人
            if (!this.searchQuery) {
                return contacts; // 如果没有搜索查询，返回原始联系人列表
            }
            return contacts.filter(contact =>
                contact.contactName.toLowerCase().includes(this.searchQuery.toLowerCase())
            );
        },
        updateFilteredContacts() {

            if (this.searchQuery) {
                const matchingGroupIds = this.filteredGroups
                    .filter(group => group.groupId !== 0 && group.filteredContacts.length > 0)
                    .map(group => group.groupId);
                this.activeNames = matchingGroupIds;
            } else {
                this.activeNames = [];
            }
            // 当搜索查询变化时，强制 Vue 重新计算 filteredGroups
            // this.$forceUpdate();
        },
        handleRowClick(row) {
            switch (this.show) {
                case 'to':
                    this.mailForm.toInput += row.email; // 设置输入框的值为点击行的值
                    if (this.mailForm.toInput !== null) {
                        this.mailForm.toInput += ";";
                    }
                    this.showToContacts = false; // 隐藏表格
                    break;
                case 'cc':
                    this.mailForm.ccInput += row.email; // 设置输入框的值为点击行的值
                    if (this.mailForm.ccInput !== null) {
                        this.mailForm.ccInput += ";";
                    }
                    this.showCcContacts = false; // 隐藏表格
                    break;
                case 'bcc':
                    this.mailForm.bccInput += row.email; // 设置输入框的值为点击行的值
                    if (this.mailForm.bccInput !== null) {
                        this.mailForm.bccInput += ";";
                    }
                    break;

            }
            this.show = null;

        },


    },
    mounted() {
    },
};
</script>
<style>
.hide-header-table .el-table__header {
    display: none;
}

.mail-write-fa {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.mail-write {
    width: 70%;
    float: left;
    margin: 0 10px;
}

.mail-contact {
    width: 30%;
    float: right;
    margin: 0 10px;
}

.mail-footer {
    width: 100%;
    text-align: center;
    margin: 100px 0;
}

.upload-file {
}

.el-upload .el-upload-dragger {
    width: 300px;
    height: 100px;
}

.ql-container {
    height: 400px;
}

</style>